import Cookies from "js-cookie";
import {loginOut, refreshAccessToken} from "../api/login";
import router from "../router";
const TokenKey = "cloud_learning_front_admin_token";
const RefreshTokenKey = "cloud_learning_front_admin_refresh_token";
const RefreshTokenKeyExpireDate = "cloud_learning_front_admin_refresh_token_expire_date";

export function getExpireTime() {
  // token刷新时间
  return 2000000;
}

export function getRefreshTokenKeyExpireDate() {
  return Cookies.get(RefreshTokenKeyExpireDate);
}

export function getToken() {
  // 用户登录token
  return Cookies.get(TokenKey);
}

export function refreshAccessTokenSetTimeout(timestamp) {
  clearTimeout(window.adminInterval);
  window.adminInterval = setTimeout(() => {
    // eslint-disable-next-line no-use-before-define
    refreshTokenMethod();
  }, timestamp);
}

export function setToken(data){
  const expireData = new Date().getTime() + data.accessToken.expiresIn * 1000;
  Cookies.set(RefreshTokenKeyExpireDate, expireData);
  Cookies.set(RefreshTokenKey, data.refreshToken);
  refreshAccessTokenSetTimeout(getExpireTime());
  return Cookies.set(TokenKey, data.accessToken.value);
}

export function removeToken() {
  Cookies.remove(RefreshTokenKey);
  Cookies.remove(RefreshTokenKeyExpireDate);
  localStorage.clear();
  return Cookies.remove(TokenKey);
}

export function refreshTokenMethod() {
  const refreshToken = Cookies.get(RefreshTokenKey);
  if (!refreshToken) {
    return;
  }
  refreshAccessToken({ refreshToken: refreshToken }, res => {
    const accessToken = { expiresIn: res.expires_in, value: res.access_token };
    const refreshToken = res.refresh_token;
    refreshAccessTokenSetTimeout(getExpireTime());
    setToken({ accessToken: accessToken, refreshToken: refreshToken });
  }).catch(() => {
    loginOut()
    router.push("/login")
  });
}

// 刷新Token
export function refreshToken() {
  const tokenKeyExpireDate = getRefreshTokenKeyExpireDate()
  if (tokenKeyExpireDate) {
    const resetTimer = Math.floor(Number(tokenKeyExpireDate) - new Date().getTime())
    if (resetTimer <= 600000) {
      console.log(new Date(), "更新token")
      refreshAccessTokenSetTimeout(15)
    }
  }
}
